import { fourDotsSpinnerSvg } from '@/assets/svg/loading'
import { MenuListType } from '@/types/menu'
import { processRoute } from '@/utils/menu'
import { ElLoading, ElMessage } from 'element-plus'
import { asyncRoutes } from '@/router/modules/asyncRoutes' // 用作备份数据
import { RoutesAlias } from '@/router/modules/routesAlias'
import axios from 'axios'

// 从环境变量获取API基础路径
const API_BASE_URL = import.meta.env.VITE_API_URL || 'http://localhost:8080';
const API_PREFIX = import.meta.env.VITE_BASE_URL || '/api';

// 菜单接口路径
const MENU_API_ENDPOINT = '/system/menu/my';
// 菜单管理相关接口
const MENU_LIST_ENDPOINT = '/menu/list';       // 菜单列表查询接口
const MENU_ADD_ENDPOINT = '/menu/add';         // 添加菜单接口
const MENU_UPDATE_ENDPOINT = '/menu/update';   // 更新菜单接口
const MENU_DELETE_ENDPOINT = '/user/del';      // 批量删除接口

// 创建axios实例
const axiosInstance = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  }
});

// 设置请求拦截器，添加认证令牌
axiosInstance.interceptors.request.use(
  (config) => {
    // 从localStorage获取token并添加Bearer前缀
    const token = localStorage.getItem('token');
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 菜单接口
export const menuService = {
  // 获取菜单列表，从服务器API获取
  getMenuList(
    delay: number = 300
  ): Promise<{ menuList: MenuListType[]; closeLoading: () => void }> {
    // 显示加载动画
    const loading = ElLoading.service({
      lock: true,
      background: 'rgba(0, 0, 0, 0)',
      svg: fourDotsSpinnerSvg,
      svgViewBox: '0 0 40 40'
    });

    // 设置超时，确保loading不会一直显示
    const loadingTimer = setTimeout(() => {
      loading.close();
    }, 10000);

    // 完整的API URL
    const menuApiUrl = API_PREFIX + MENU_API_ENDPOINT;
    console.log('请求菜单数据，URL:', API_BASE_URL + menuApiUrl);

    // 创建Promise处理菜单获取逻辑
    return new Promise((resolve) => {
      // 检查用户是否已登录
      const token = localStorage.getItem('token');
      const isLoggedIn = !!token;
      
      // 未登录时，直接使用默认菜单，不发送请求
      if (!isLoggedIn) {
        console.log('用户未登录，使用默认菜单');
        const processedMenuList = asyncRoutes.map(route => processRoute(route));
        clearTimeout(loadingTimer);
        
        resolve({
          menuList: processedMenuList,
          closeLoading: () => loading.close()
        });
        return;
      }
      
      // 用户已登录，从后端API获取菜单数据
      axiosInstance.get(menuApiUrl)
        .then(response => {
          const responseData = response.data;
          
          // 检查API响应结构
          if (!responseData || responseData.code !== 200 || !Array.isArray(responseData.data)) {
            console.warn('菜单API返回格式不符合预期，使用默认菜单:', responseData);
            throw new Error('API响应格式错误');
          }
          
          // 处理API返回的菜单数据
          const menuData = this.processApiResponseData(responseData.data);
          const processedMenuList = menuData.map((route: any) => processRoute(route));
          
          clearTimeout(loadingTimer);
          console.log('成功获取菜单数据，菜单数量:', processedMenuList.length);
          
          // 返回处理后的菜单数据和关闭加载动画的函数
        resolve({
          menuList: processedMenuList,
          closeLoading: () => loading.close()
          });
        })
        .catch(error => {
          // 记录错误
          console.error('获取菜单数据失败，使用默认菜单:', error);
          
          // 使用备用菜单数据
          const processedMenuList = asyncRoutes.map(route => processRoute(route));
          clearTimeout(loadingTimer);
          
          // 显示错误提示
          ElMessage.warning({
            message: '获取菜单失败，使用默认菜单',
            type: 'warning',
            duration: 3000
          });
          
          // 返回备用菜单数据
          resolve({
            menuList: processedMenuList,
            closeLoading: () => loading.close()
          });
        });
    });
  },

  // 获取菜单管理列表数据
  async getMenuListForManagement(): Promise<any[]> {
    try {
      const apiUrl = `${API_PREFIX}${MENU_LIST_ENDPOINT}`;
      console.log('API: 请求菜单管理列表, URL:', apiUrl);
      
      const response = await axiosInstance.get(apiUrl);
      console.log('API: 菜单列表接口原始响应:', response);
      
      // 检查响应结构
      if (response.data) {
        // 检查常见的数据格式
        // 格式1: { code: 200, data: [...] }
        if (response.data.code === 200 && Array.isArray(response.data.data)) {
          console.log('API: 获取菜单管理列表成功, 数量:', response.data.data.length);
          return response.data.data;
        }
        // 格式2: { code: 200, data: { rows: [...] } }
        else if (response.data.code === 200 && response.data.data && Array.isArray(response.data.data.rows)) {
          console.log('API: 获取菜单管理列表成功 (rows格式), 数量:', response.data.data.rows.length);
          return response.data.data.rows;
        }
        // 格式3: { code: 200, data: { list: [...] } }
        else if (response.data.code === 200 && response.data.data && Array.isArray(response.data.data.list)) {
          console.log('API: 获取菜单管理列表成功 (list格式), 数量:', response.data.data.list.length);
          return response.data.data.list;
        }
        // 格式4: 直接返回数组
        else if (Array.isArray(response.data)) {
          console.log('API: 获取菜单管理列表成功 (直接数组), 数量:', response.data.length);
          return response.data;
        }
        // 格式5: { data: [...] }
        else if (response.data.data && Array.isArray(response.data.data)) {
          console.log('API: 获取菜单管理列表成功 (无code), 数量:', response.data.data.length);
          return response.data.data;
        }
        // 不支持的格式，但有返回数据
        else {
          console.warn('API: 菜单列表数据格式不符合预期:', response.data);
          if (response.data.data && typeof response.data.data === 'object') {
            // 尝试将对象转为数组
            const dataArray = Object.values(response.data.data).filter(item => typeof item === 'object');
            if (dataArray.length > 0) {
              console.log('API: 尝试将数据转换为数组格式，数量:', dataArray.length);
              return dataArray;
            }
          }
          
          // 无法处理的格式，返回空数组
          ElMessage.warning('菜单数据格式异常，请联系管理员');
          return [];
        }
      } else {
        // 响应格式异常
        console.error('API: 菜单列表接口响应格式异常:', response);
        ElMessage.error('获取菜单列表失败，响应格式异常');
        return [];
      }
    } catch (error) {
      // 网络错误或其他异常
      console.error('API: 获取菜单管理列表请求失败:', error);
      ElMessage.error('获取菜单列表失败，请检查网络连接');
      return [];
    }
  },

  // 添加菜单
  async addMenu(menuData: any): Promise<any> {
    try {
      const apiUrl = `${API_PREFIX}${MENU_ADD_ENDPOINT}`;
      console.log('添加菜单，URL:', apiUrl, '参数:', menuData);
      
      const response = await axiosInstance.post(apiUrl, menuData);
      
      if (response.data && response.data.code === 200) {
        console.log('添加菜单成功:', response.data);
        return response.data.data;
      } else {
        console.error('添加菜单失败:', response.data);
        throw new Error(response.data?.message || '添加菜单接口返回异常');
      }
    } catch (error: any) {
      console.error('添加菜单请求失败:', error);
      throw new Error(error.response?.data?.message || error.message || '添加菜单失败');
    }
  },

  // 更新菜单
  async updateMenu(menuData: any): Promise<any> {
    try {
      const apiUrl = `${API_PREFIX}${MENU_UPDATE_ENDPOINT}`;
      console.log('更新菜单，URL:', apiUrl, '参数:', menuData);
      
      const response = await axiosInstance.put(apiUrl, menuData);
      
      if (response.data && response.data.code === 200) {
        console.log('更新菜单成功:', response.data);
        return response.data.data;
      } else {
        console.error('更新菜单失败:', response.data);
        throw new Error(response.data?.message || '更新菜单接口返回异常');
      }
    } catch (error: any) {
      console.error('更新菜单请求失败:', error);
      throw new Error(error.response?.data?.message || error.message || '更新菜单失败');
    }
  },

  // 删除菜单
  async deleteMenu(ids: number[]): Promise<any> {
    try {
      const apiUrl = `${API_PREFIX}${MENU_DELETE_ENDPOINT}`;
      console.log('删除菜单，URL:', apiUrl, '参数:', { id: ids });
      
      const response = await axiosInstance.delete(apiUrl, {
        data: { id: ids } // 按照接口规范传递id数组
      });
      
      if (response.data && response.data.code === 200) {
        console.log('删除菜单成功:', response.data);
        return response.data.data;
      } else {
        console.error('删除菜单失败:', response.data);
        throw new Error(response.data?.message || '删除菜单接口返回异常');
      }
    } catch (error: any) {
      console.error('删除菜单请求失败:', error);
      throw new Error(error.response?.data?.message || error.message || '删除菜单失败');
    }
  },

  // 处理API返回的数据
  processApiResponseData(apiData: any[]): MenuListType[] {
    try {
      // 检查数据格式
      if (!Array.isArray(apiData)) {
        console.error('API数据不是数组格式');
        throw new Error('API数据格式错误');
      }

      // 转换组件路径字符串为实际路径
      return apiData.map(menuItem => {
        const processedItem = { ...menuItem };
        
        // 处理组件字段，将RoutesAlias字符串转换为实际路径
        if (typeof processedItem.component === 'string') {
          if (processedItem.component.startsWith('RoutesAlias.')) {
            const aliasKey = processedItem.component.replace('RoutesAlias.', '');
            processedItem.component = (RoutesAlias as any)[aliasKey] || '';
          }
        }
        
        // 处理子菜单
        if (Array.isArray(processedItem.children) && processedItem.children.length > 0) {
          processedItem.children = this.processApiResponseData(processedItem.children);
        }
        
        // 确保必要的字段存在
        if (!processedItem.redirect) {
          processedItem.redirect = '';
        }
        
        return processedItem;
      });
    } catch (error) {
      console.error('处理API数据出错:', error);
      throw error;
    }
  },

  // 将嵌套的菜单结构扁平化为一维数组（包含所有子菜单）
  flattenMenusWithChildren(menus: any[]): any[] {
    if (!Array.isArray(menus)) {
      console.warn('flattenMenusWithChildren: 输入不是数组');
      return [];
    }

    let result: any[] = [];
    
    for (const menu of menus) {
      // 添加当前菜单到结果
      result.push({...menu});
      
      // 递归处理子菜单
      if (menu.children && Array.isArray(menu.children) && menu.children.length > 0) {
        const flattenedChildren = this.flattenMenusWithChildren(menu.children);
        result = result.concat(flattenedChildren);
      }
    }
    
    return result;
  },

  // 退出登录，清空localStorage
  logout(): void {
    // 清空localStorage中的所有内容
    localStorage.clear();
    
    // 提示用户已退出登录
    ElMessage.success({
      message: '已成功退出登录',
      type: 'success',
      duration: 2000
    });
  },

  // 使用固定的菜单数据（用于演示或者开发测试）
  async useFixedMenuData(): Promise<any[]> {
    try {
      console.log('API: 使用固定菜单数据');
      
      // 模拟后端返回的固定数据
      const fixedResponse = {
        "code": 200,
        "msg": "ok",
        "message": "ok",
        "data": [
          {
            "id": 1,
            "created_at": "2022-10-19 18:27:57",
            "updated_at": "2022-10-19 20:53:45",
            "meta": {
              "icon": "&#xe721;",
              "keepAlive": false,
              "title": "menus.dashboard.title"
            },
            "component": "RoutesAlias.Home",
            "name": "Dashboard",
            "parent_id": 0,
            "sort": 0,
            "path": "/dashboard",
            "redirect": "",
            "children": [
              {
                "id": 101,
                "created_at": "2022-10-19 19:15:38",
                "updated_at": "2022-10-19 19:15:38",
                "meta": {
                  "keepAlive": true,
                  "title": "menus.dashboard.console"
                },
                "component": "RoutesAlias.Dashboard",
                "name": "Console",
                "parent_id": 1,
                "sort": 0,
                "path": "console",
                "redirect": "",
                "children": null
              },
              {
                "id": 102,
                "created_at": "2022-10-19 19:15:43",
                "updated_at": "2022-10-19 20:53:55",
                "meta": {
                  "keepAlive": true,
                  "title": "menus.dashboard.analysis"
                },
                "component": "RoutesAlias.Analysis",
                "name": "Analysis",
                "parent_id": 1,
                "sort": 0,
                "path": "analysis",
                "redirect": "",
                "children": null
              },
              {
                "id": 103,
                "created_at": "2022-10-19 20:28:24",
                "updated_at": "2022-10-19 20:45:36",
                "meta": {
                  "keepAlive": true,
                  "showTextBadge": "new",
                  "title": "menus.dashboard.ecommerce"
                },
                "component": "RoutesAlias.Ecommerce",
                "name": "Ecommerce",
                "parent_id": 1,
                "sort": 0,
                "path": "ecommerce",
                "redirect": "",
                "children": null
              }
            ]
          },
          {
            "id": 2,
            "created_at": "2022-10-19 18:27:59",
            "updated_at": "2022-10-19 18:27:59",
            "meta": {
              "icon": "&#xe86e;",
              "keepAlive": false,
              "title": "menus.user.title"
            },
            "component": "RoutesAlias.Home",
            "name": "User",
            "parent_id": 0,
            "sort": 0,
            "path": "/user",
            "redirect": "",
            "children": [
              {
                "id": 201,
                "created_at": "2022-10-21 08:57:26",
                "updated_at": "2022-11-06 12:00:03",
                "meta": {
                  "keepAlive": true,
                  "title": "menus.user.account"
                },
                "component": "RoutesAlias.Account",
                "name": "Account",
                "parent_id": 2,
                "sort": 10,
                "path": "account",
                "redirect": "",
                "children": null
              },
              {
                "id": 204,
                "created_at": "2022-11-02 16:40:14",
                "updated_at": "2022-11-06 12:01:13",
                "meta": {
                  "isHide": true,
                  "isHideTab": true,
                  "keepAlive": true,
                  "title": "menus.user.userCenter"
                },
                "component": "RoutesAlias.UserCenter",
                "name": "UserCenter",
                "parent_id": 2,
                "sort": 3,
                "path": "user",
                "redirect": "",
                "children": null
              },
              {
                "id": 203,
                "created_at": "2022-10-24 10:51:20",
                "updated_at": "2022-11-06 10:22:18",
                "meta": {
                  "keepAlive": true,
                  "title": "menus.user.role"
                },
                "component": "RoutesAlias.Role",
                "name": "Role",
                "parent_id": 2,
                "sort": 1,
                "path": "role",
                "redirect": "",
                "children": null
              },
              {
                "id": 202,
                "created_at": "2022-10-21 09:05:47",
                "updated_at": "2022-11-05 11:40:52",
                "meta": {
                  "keepAlive": false,
                  "title": "menus.user.department"
                },
                "component": "RoutesAlias.Department",
                "name": "Department",
                "parent_id": 2,
                "sort": 0,
                "path": "department",
                "redirect": "",
                "children": null
              }
            ]
          },
          {
            "id": 3,
            "created_at": "2022-10-19 18:28:00",
            "updated_at": "2022-10-19 18:28:00",
            "meta": {
              "icon": "&#xe8a4;",
              "keepAlive": false,
              "title": "menus.menu.title"
            },
            "component": "RoutesAlias.Home",
            "name": "Menu",
            "parent_id": 0,
            "sort": 0,
            "path": "/menu",
            "redirect": "",
            "children": [
              {
                "id": 301,
                "created_at": "2022-11-05 11:42:16",
                "updated_at": "2022-11-06 12:01:18",
                "meta": {
                  "authList": [
                    {
                      "auth_mark": "add",
                      "id": 3011,
                      "title": "新增"
                    },
                    {
                      "auth_mark": "edit",
                      "id": 3012,
                      "title": "编辑"
                    },
                    {
                      "auth_mark": "delete",
                      "id": 3013,
                      "title": "删除"
                    }
                  ],
                  "icon": "&#xe8a4;",
                  "keepAlive": true,
                  "title": "menus.menu.menu"
                },
                "component": "RoutesAlias.Menu",
                "name": "Menus",
                "parent_id": 3,
                "sort": 3,
                "path": "menu",
                "redirect": "",
                "children": null
              },
              {
                "id": 302,
                "created_at": "2022-11-05 11:44:48",
                "updated_at": "2022-11-06 12:01:24",
                "meta": {
                  "authList": [
                    {
                      "auth_mark": "add",
                      "id": 3021,
                      "title": "新增"
                    },
                    {
                      "auth_mark": "edit",
                      "id": 3022,
                      "title": "编辑"
                    },
                    {
                      "auth_mark": "delete",
                      "id": 3023,
                      "title": "删除"
                    }
                  ],
                  "icon": "&#xe831;",
                  "keepAlive": true,
                  "showTextBadge": "new",
                  "title": "menus.menu.permission"
                },
                "component": "RoutesAlias.Permission",
                "name": "Permission",
                "parent_id": 3,
                "sort": 2,
                "path": "permission",
                "redirect": "",
                "children": null
              },
              {
                "id": 303,
                "created_at": "2022-11-05 11:45:05",
                "updated_at": "2022-11-06 12:01:31",
                "meta": {
                  "icon": "&#xe676;",
                  "keepAlive": true,
                  "title": "menus.menu.nested"
                },
                "component": "",
                "name": "Nested",
                "parent_id": 3,
                "sort": 1,
                "path": "nested",
                "redirect": "",
                "children": null
              }
            ]
          },
          {
            "id": 4,
            "created_at": "2022-10-19 18:28:00",
            "updated_at": "2022-10-19 19:08:13",
            "meta": {
              "icon": "&#xe7b9;",
              "keepAlive": false,
              "title": "menus.system.title"
            },
            "component": "RoutesAlias.Home",
            "name": "System",
            "parent_id": 0,
            "sort": 0,
            "path": "/system",
            "redirect": "",
            "children": [
              {
                "id": 401,
                "created_at": "2022-11-06 10:18:06",
                "updated_at": "2022-11-06 10:21:56",
                "meta": {
                  "keepAlive": true,
                  "title": "menus.system.setting"
                },
                "component": "RoutesAlias.Setting",
                "name": "Setting",
                "parent_id": 4,
                "sort": 1,
                "path": "setting",
                "redirect": "",
                "children": null
              },
              {
                "id": 402,
                "created_at": "2022-11-06 10:18:16",
                "updated_at": "2022-11-06 10:21:49",
                "meta": {
                  "keepAlive": true,
                  "title": "menus.system.api"
                },
                "component": "RoutesAlias.Api",
                "name": "Api",
                "parent_id": 4,
                "sort": 1,
                "path": "api",
                "redirect": "",
                "children": null
              },
              {
                "id": 403,
                "created_at": "2022-11-06 10:18:23",
                "updated_at": "2022-11-06 10:21:07",
                "meta": {
                  "keepAlive": true,
                  "title": "menus.system.log"
                },
                "component": "RoutesAlias.Log",
                "name": "Log",
                "parent_id": 4,
                "sort": 1,
                "path": "log",
                "redirect": "",
                "children": null
              }
            ]
          },
          {
            "id": 5,
            "created_at": "2022-10-21 08:44:55",
            "updated_at": "2022-11-06 10:23:28",
            "meta": {
              "icon": "&#xe816;",
              "keepAlive": false,
              "title": "menus.safeguard.title"
            },
            "component": "RoutesAlias.Home",
            "name": "Safeguard",
            "parent_id": 0,
            "sort": 0,
            "path": "/safeguard",
            "redirect": "",
            "children": [
              {
                "id": 501,
                "created_at": "2022-11-06 10:23:01",
                "updated_at": "2022-11-06 10:24:16",
                "meta": {
                  "keepAlive": true,
                  "title": "menus.safeguard.server"
                },
                "component": "RoutesAlias.Server",
                "name": "Server",
                "parent_id": 5,
                "sort": 1,
                "path": "server",
                "redirect": "",
                "children": null
              }
            ]
          }
        ]
      };
      
      console.log('API: 使用固定菜单数据，数量:', fixedResponse.data.length);
      
      // 直接返回顶级菜单，不展平结构
      return fixedResponse.data;
    } catch (error) {
      console.error('API: 处理固定菜单数据失败:', error);
      return [];
    }
  }
}